<?php
##############################################
#
#   抽奖
# @ Time : 2016-12-22 - 下午11:46:58
# @ Author : JiangYongWei <1085562810@qq.com>
# @ Encoding : UTF-8 language : PHP
#
##############################################

namespace Home\Controller;
use Home\Model\PrizeModel;
use Home\Model\PrizeRecordModel;
use Home\Model\PartUserModel;
use Home\Model\LotteryRulesModel;

class PrizeDrawController extends BaseController
{
    
    public function index()
    {
        if(!IS_AJAX)
            return false;

        $prize_model = new PrizeModel();
        $rules_model = new LotteryRulesModel();
        $part_user_model = new PartUserModel();

        //答题数量设置
        $gopricesocre = M('answer_num')->getField('gopricesocre');
        //最后一次答题信息
        $last_answerinfo = M('answer_formalinfo')->where("user_id=$this->user_id AND status = 1")->order('id desc')->find();
        if($last_answerinfo['score'] < $gopricesocre)
            $this->ajaxReturn(array('status' => -5, 'message' => '答题分数不足不能抽奖！'));

        //查询规则设置和是否过期
        $lottery_data = $rules_model -> getRules($r_id = 1);
        if(time() < $lottery_data['start_time'])
            $this->ajaxReturn(array('status' => -1, 'message' => '该抽奖活动还没有开始！'));
        if(time() > $lottery_data['end_time'])
            $this->ajaxReturn(array('status' => -2, 'message' => '该抽奖活动已过期！'));

        //判断用户当天抽奖数，检查是否有抽奖机会
        $starttime  = strtotime(date('Y-m-d 00:00:00',time()));
        $endtime = strtotime(date('Y-m-d 23:59:59',time()));
        $time = array();
        $time['starttime'] = $starttime;
        $time['endtime'] = $endtime;
        $day_prize_count = $part_user_model -> getUserDayPrizeCount($this->user_id,$time);
        if($day_prize_count >= $lottery_data['most_num'])
            $this->ajaxReturn(array('status' => -3, 'message' => '你今天的抽奖机会用完了，明天再抽吧！'));

        //判断用户是否有抽奖机会
        $luckdraw_num = $prize_model -> getLuckdrawNum($this->user_id); //获取用户的可抽奖数
        if($luckdraw_num < 1){
            $this->ajaxReturn(array('status' => -4, 'message' => '您的抽奖机会已经使用完!'));
           /* //防止用户按返回键回到抽奖页面进行抽奖输出json格式代码
            echo "<html><head><meta http-equiv=\"Content-Type\" content=\"tex/html; charset=utf-8\"><script>window.alert('您的抽奖机会已经使用完。');window.location.href='/';</script></head></html>";
            exit;*/
        }

        /*//检查是否还有奖品可抽
        $prize_data = $prize_model -> getPrizeList();
        $total_surplus_num = 0;
        foreach ($prize_data as $k => $v) {
            $total_surplus_num += $v['surplus_num'];
            if($v['p_id'] == 6){
                unset($prize_data[$k]);
            }
        }
        //是否还有奖品可抽
        if($total_surplus_num <= 0){
           
                $this->ajaxReturn(array('status' => 2, 'message' => '亲，奖品已经被抽完了，下次再来抽吧！!'));
        }*/

        /*
        $record_model = new PrizeRecordModel();
        //查询我的奖品
        $user_prize = $record_model -> getUserWinningPrize($this->user_id);
        $this->assign('user_prize', $user_prize);

        //获取所有用户中奖记录
        $all_user_prize = $record_model -> getAllWinningPrize();
        $this->assign('all_user_prize', $all_user_prize);*/

        /*
        //区分上面，进行正常的ajax请求判断
        if($luckdraw_num < 1 && IS_AJAX){
            $this->ajaxReturn(array('status' => 4, 'message' => '对不起，你没有抽奖机会了，可通过分享拉票链接获得抽奖机会'));
            
        }*/

        //有符合抽奖条件
        if(IS_AJAX){
            $this->ajaxReturn(array('status' => 1,'url'=>U("PrizeDraw/prizeDraw")));
        }

    }


    //抽奖页面
    public function prizeDraw()
    {
        //查询规则设置
        $rules_model = new LotteryRulesModel();
        $lottery_data = $rules_model -> getRules($r_id = 1);

        $record_model = new PrizeRecordModel();
        //获取所有用户中奖记录
        $all_user_prize = $record_model -> getAllWinningPrize();
        $all_user_prize = array_slice($all_user_prize,0,10);

        //奖品列表
        $prize_model = new PrizeModel();
        $prize_data = $prize_model -> getPrizeList();
        $prizename = array();
        foreach ($prize_data as $k => $v)
        {
            $prizename[] = $v['prize_name'];
        }
        //var_dump($prizename);die;
        //session('prizename',$prizename);
        $num = $res = M('users')->where("id=$this->user_id")->getField('luckdraw_num');
        $this->assign('num', $num);
        $this->assign('all_user_prize', $all_user_prize);
        $this->assign('lottery_data', $lottery_data);
        $this->assign('prizename', $prizename);
        $this->display('turntable');
    }

    //处理中奖抽奖信息
    public function userprizeinfo()
    {
        //抽中奖品信息
        $prizename = I('prizename');
        $prize = M('prize')->where(array('prize_name'=>$prizename))->find();

        //抽奖纪录
        $part_user_model = new PartUserModel();
        $part_id =$part_user_model -> insertRecord($this->user_id);

        //中奖纪录
        $record_model = new PrizeRecordModel();
        $record_id = $record_model -> insertWinningRecord($prize,$this->user_id);
        if($record_id)
        {
            //减少用户抽奖数
            $res = M('users')->where("id=$this->user_id")->setDec('luckdraw_num');
            if($res)
                $this->ajaxReturn(array('status' => 1));
            else
                $this->ajaxReturn(array('status' => -1,'message'=>"网络繁忙，请重试！"));
        }
        $this->ajaxReturn(array('status' => -2,'message'=>"网络繁忙，请重试！"));
    }


    //检查是否还有抽奖机会
    public function check_prize_change()
    {
        $prize_model = new PrizeModel();
        $rules_model = new LotteryRulesModel();
        $part_user_model = new PartUserModel();

        //查询规则设置和是否过期
        $lottery_data = $rules_model -> getRules($r_id = 1);
        if(time() < $lottery_data['start_time'])
            $this->ajaxReturn(array('status' => -1, 'message' => '该抽奖活动还没有开始！'));
        if(time() > $lottery_data['end_time'])
            $this->ajaxReturn(array('status' => -2, 'message' => '该抽奖活动已过期！'));

        //判断用户当天抽奖数是否大于设置抽奖数，检查是否有抽奖机会
        $starttime  = strtotime(date('Y-m-d 00:00:00',time()));
        $endtime = strtotime(date('Y-m-d 23:59:59',time()));
        $time = array();
        $time['starttime'] = $starttime;
        $time['endtime'] = $endtime;
        $day_prize_count = $part_user_model -> getUserDayPrizeCount($this->user_id,$time);
        if($day_prize_count >= $lottery_data['most_num'])
            $this->ajaxReturn(array('status' => -3, 'message' => '你今天的抽奖机会用完了，明天再抽吧！'));

        //判断用户是否有抽奖机会
        $luckdraw_num = $prize_model -> getLuckdrawNum($this->user_id); //获取用户的可抽奖数
        if($luckdraw_num < 1){
            $this->ajaxReturn(array('status' => -4, 'message' => '您的抽奖机会已经使用完<br />请获得机会后再抽奖!'));
        }
        //有符合抽奖条件
        if(IS_AJAX){
            $this->ajaxReturn(array('status' => 1));
        }
    }

    //抽奖
    /*
     public function prizeDraw(){

        $this -> display('turntable');DIE;
        $prize_model = new PrizeModel();
        
        $luckdraw_num = $prize_model -> getLuckdrawNum($this->user_id); //getLuckdrawNum($user_id = 1)获取用户的可抽奖数
        if($luckdraw_num < 1){
            //防止用户按返回键回到抽奖页面进行抽奖，要弹出提示框
            echo "<html><head><meta http-equiv=\"Content-Type\" content=\"tex/html; charset=utf-8\"><script>window.alert('您的抽奖机会已经使用完。');window.location.href='/';</script></head></html>";
            exit;
        }
        //获取该规则奖品
        $prize_arr = $prize_model -> getPrizeList($r_id = 1); //getPrizeList($r_id = 1)
        //按奖品数量来计算中奖概率
        foreach ($prize_arr as $key => $val) {
            $arr[$val['p_id']] = $val['prize_num'];
        }

        //计算概率
        $tem_arr = $this -> Draw($arr);
        

        //减去一个奖品
        $prize_model -> reduceOnePrize($tem_arr['p_id']);
        //插入参与抽奖记录
        $part_user_model = new PartUserModel();
        $part_user_model -> insertRecord($tem_arr,$this->user_id);
        //如果已中奖插入中奖记录表
        if($tem_arr['prize_type'] != 3){
            $record_model = new PrizeRecordModel();
            $record_model -> insertWinningRecord($tem_arr,$this->user_id);
        }
        //每抽奖一次就减去该用户抽奖数
        $result = $prize_model -> reduceUserNum($this->user_id);  //reduceUserNum($user_id = 1)
        if($result){
            $this -> redirect('show',array('p_id'=>$tem_arr['p_id']));
        }else{
            exit('程序发送错误');
        }
    }*/

    //递归调用抽奖，判断抽到的奖品是否大于每天最多的中奖数量，
    //如果大于就继续抽奖，如果抽到的是谢谢参与就返回
    //注：奖品类型是3的为谢谢参与，表示没有抽到奖品
    public function Draw($arr){
        $prize_model = new PrizeModel();
        $record_model = new PrizeRecordModel();
        $p_id = $this -> getRand($arr);

        //获取奖品信息
        $prize = $prize_model->getPrize($p_id);
        //获取该奖品每天最多中奖数量
        $max_winning = $prize['max_winning'];
        //奖品类型
        $prize_type = $prize['prize_type'];
        //该奖品今天已中奖总数
        $number = $record_model -> countRecord($p_id);
        //获取用户在活动期间抽中的实物礼品总数
        $matter_count = $record_model -> getReal($this->user_id);  //getReal($user_id)
        //获取规则设置的每个用户在活动期间最多只能抽中实物礼品次数
        $matter_num = $record_model -> getMatterNum($r_id = 1);  //getMatterNum($r_id = 1)
        //file_put_contents('matter_num.txt',$matter_count.'/'.$matter_num);
        //如果不是谢谢参与而且每天该奖品中奖数量大于设置的每天最多中奖数量,
        //每个用户抽中实体物品总数大于规则设置的抽中实体物品次数就继续递归抽奖，
        // echo $prize_type."<br/>";
        // echo $number."<br/>";
        // echo $max_winning."<br/>";
        // echo $matter_count."[[[<br/>";
        // echo $matter_num;
        // var_dump($prize_type != 3 && $number >= $max_winning && $matter_count >= $matter_num);
        // exit;
        if($prize_type != 3){
            if($number >= $max_winning || ($prize_type == 2 && $matter_count >= $matter_num)){ 
                return $this->Draw($arr);
            }else{
                return array('p_id' =>$p_id, 'prize_type' => $prize_type, 'prize_name' => $prize['prize_name']);//返回奖品id和奖品类型
            }
        } else {
            return array('p_id' =>$p_id, 'prize_type' => $prize_type, 'prize_name' => $prize['prize_name']);//返回奖品id和奖品类型
        }
    }

    /*计算概率*/
    public function getRand($proArr) {
        $result = '';
        /*概率数组的总概率精度*/
        $proSum = array_sum($proArr);//总奖品数
        /*概率数组循环*/
        foreach ($proArr as $key => $proCur) {//2,5,6,8,
            /*相当于每次只能够抽取其中的一个奖项，没抽中就开始抽下一个奖项，直到最后*/
            $randNum = mt_rand(1, $proSum);//随机返回区间中一个数字
            if ($randNum <= $proCur) {
                /*表示抽中奖了，该奖品应该要减一*/
                $result = $key;//$key为奖品id
                break;
            } else {
                /*没有抽中就不能再抽了，直到敲到下一个金蛋*/
                $proSum -= $proCur;
            }
        }

        unset ($proArr);
        return $result;
    }

    public function show(){
           
            $p_id = I('get.p_id');
            $proId = I('get.proId');
            $prize_model = new PrizeModel();
            $prize = $prize_model->getPrize($p_id);

            //用户电话
            $userinfo = M('userinfo')->field('user_mobile')->where(array('id'=>$this->user_id))->find();
        
            //添加抵用券红包接口接口
            if($prize['prize_type'] == 1){
                $params = array(
                  'act' => 'setbonus', 
                  'app_user_id' => $this->token,
                  'min_goods_amount' => $prize['min_goods_amount'],
                  'type_money' => "{$prize['type_momey']}",
                  'use_end_date' => $prize['use_end_date'],
                  'use_start_date' => $prize['use_start_date'],
                  'mobile' => $userinfo['user_mobile']
                );
                ksort($params);
                $url1 = http_build_query($params);
                unset($params['act']);
                $url = http_build_query($params);
                $str2 = md5($url);
                $str3 = mb_substr($str2, 0, 10);
                $signature = md5($str2.$str3);
                $url1 = $url1.'&signature='.$signature;
                $data = httpUrl(C('bonus'), $url1, 0, $header = array(), $verify = false);
                $result = json_decode($data,true);
                /* var_dump($result);
                exit; */
                if($result['state'] == 0){
                  file_put_contents('./Public/interface_log/bonus.log', var_export($params, true)."\r\n\n", FILE_APPEND);
                }else{
                    $this->error('亲，服务器繁忙，请稍后再抽！', U('index'), 2);
                }

            //添加实物接口
            }elseif($prize['prize_type'] == 2){
                 $params = array(
                  'act' => 'setmatreail', 
                  'app_user_id' => $this->token,
                  'goods_sn' => $prize['goods_sn'],
                  'is_shipping' => $prize['is_shipping'],
                  'type_money' => "{$prize['type_momey']}",
                  'use_end_date' => $prize['use_end_date'],
                  'use_start_date' => $prize['use_start_date'],
                  'mobile' => $userinfo['user_mobile']
                );
                ksort($params);
                $url1 = http_build_query($params);
                unset($params['act']);
                $url = http_build_query($params); 
                $str2 = md5($url);
                $str3 = mb_substr($str2, 0, 10);
                $signature = md5($str2.$str3);
                $url1 = $url1.'&signature='.$signature;
                $result = httpUrl(C('matreail'), $url1, 0, $header = array(), $verify = false);
               /*  var_dump($data);
                exit; */
                if($result['state'] == 0){
                   file_put_contents('./Public/interface_log/matreail.log', var_export($params, true)."\r\n\n", FILE_APPEND);
                }else{
                    $this->error('亲，服务器繁忙，请稍后再抽！', U('index'), 2);
                }
            }
            elseif($prize['prize_type'] == 4){
                $params = array(
                    'act' => 'setcategorybonus',
                    'app_user_id' => $this->token,
                    'cat_id' => $prize['cat_id'],//商品类型id
                    'min_goods_amount' => $prize['min_goods_amount'],
                    'type_money' => "{$prize['type_momey']}",
                    'use_end_date' => $prize['use_end_date'],
                    'use_start_date' => $prize['use_start_date'],
                    'mobile' => $userinfo['user_mobile']
                );
            ksort($params);
            $url1 = http_build_query($params);
            unset($params['act']);
            $url = http_build_query($params);
            $str2 = md5($url);
            $str3 = mb_substr($str2, 0, 10);
            $signature = md5($str2.$str3);
            $url1 = $url1.'&signature='.$signature;
            $result = httpUrl(C('setcategorybonus'), $url1, 0, $header = array(), $verify = false);
              
             
            if($result['state'] == 0){
                file_put_contents('./Public/interface_log/setcategorybonus.log', var_export($params, true)."\r\n\n", FILE_APPEND);
            }else{
                $this->error('亲，服务器繁忙，请稍后再抽！', U('index'), 2);
            }
        }

            $appUrl = M('activity') ->field('appurl,iosappurl')-> where("activity_id = 2") -> find();
        
            $type = $this->get_device_type();
            if ($type == "android")
            {
                $this -> assign('url', $appUrl['appurl']);
            }
            else if ($type == "ios") {
                $this -> assign('url', $appUrl['iosappurl']);
            }
            $this -> assign('data', $prize);
            $this -> assign('proId',$proId);
            $this -> display('game_result');
    }
    
    public function getShow(){
       $signature = $_GET['signature'];
       unset($_GET['signature']);
       unset($_GET['act']);
       //sort($_GET);
       //var_dump($_GET);
       $url = http_build_query($_GET);
       $str2 = md5($url);
       $str3 = mb_substr($str2, 0, 10);
       $signature_1 = md5($str2.$str3);
       if($signature == $signature_1){
           echo 1;
       }else{
           echo 2;
       }     
    }
    
    /**
     *领取奖品
     * @Date 201704
     * @Author Linsenquan
     */
    public function getPrize()
    {
      
        //var_dump($prize);
        $prize =M('PrizeRecord')->alias('a')
                ->join('left join mt_prize pr ON pr.p_id = a.prize_id')
                ->field('pr.prize_name')
                ->where(array('a.user_id'=>$this->user_id))
                ->select();
                
        if(count($prize)==1){
            $prize = $prize[0]['prize_name'];
            $show = 1;
        }else if (count($prize) > 1){
            $prize = $prize[0]['prize_name'].'等多个礼品';
            $show = 1;
        }else {
            $show = 0;
        }

        $appUrl = M('activity') ->field('appurl,iosappurl')-> where("activity_id = 2") -> find();
        
        $type = $this->get_device_type();
        if ($type == "android")
        {
            $this -> assign('url', $appUrl['appurl']);
        }
        else if ($type == "ios") {
            $this -> assign('url', $appUrl['iosappurl']);
        }
        $this->assign('show',$show);
        $this->assign('data',$prize);
        //var_dump($show);
        $this->display('getprize');
    }


    /**
     *判断ios
     * @return string
     * @Date 201703
     * @Author Linsenquan
     */
    public function get_device_type()
    {
        //全部变成小写字母
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        $type = 'other';
        //分别进行判断
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            $type = 'ios';
        }

        if(strpos($agent, 'android'))
        {
            $type = 'android';
        }
        return $type;
    }
}
